<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="所属题库">
        <el-radio-group v-model="form.bankFlag">
          <el-radio label="0" border style="margin: 0">基础题库</el-radio>
          <el-radio label="1" border style="margin: 0">考试题库</el-radio>
        </el-radio-group>
        <el-select v-model="queryParams.bankId" placeholder="所属题库">
          <el-option v-for="item in questionBank.list" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型" prop="content">
        <el-select v-model="queryParams.type" placeholder="请选择">
          <el-option key="0" label="单选" value="0"></el-option>
          <el-option key="0" label="多选" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="queryParams.content" placeholder="请输入内容" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="答案" prop="options">
        <el-input v-model="queryParams.options" placeholder="请输入答案" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="说明" prop="info">
        <el-input v-model="queryParams.info" placeholder="请输入说明" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="分析" prop="analyse">
        <el-input v-model="queryParams.analyse" placeholder="请输入分析" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ex:question:add']">新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['ex:question:edit']">修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['ex:question:remove']">删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['ex:question:export']">导出</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="importQuestion.open = true">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="42" align="left"/>
      <el-table-column label="内容" align="center" prop="content" width="300"/>
      <el-table-column label="题型" align="center" width="60">
        <template slot-scope="scope">
          {{scope.row.type == 0? '单选' : '多选' }}
        </template>
      </el-table-column>
      <el-table-column label="选项" align="center" width="400">
        <template slot-scope="scope">
          <template v-for="item in scope.row.optionList">
            <span>{{item.k}}:{{item.v}}</span><br>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="答案" align="center" width="80">
        <template slot-scope="scope">
          <template v-for="item in scope.row.answerList">
            <span>{{item}}</span><br>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="info"/>
      <el-table-column label="分析" align="center" prop="analyse"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ex:question:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ex:question:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="830px" height="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="1">
          <el-form-item label="所属题库" prop="bankId">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-radio-group v-model="form.bankFlag">
                  <el-radio label="0" border style="margin: 0">基础题库</el-radio>
                  <el-radio label="1" border style="margin: 0">考试题库</el-radio>
                </el-radio-group>
              </el-col>
              <el-col :span="1.5">
                <el-select v-model="form.bankId" placeholder="请选择所属题库">
                  <el-option v-for="item in questionBank.list" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="题型" prop="type">
            <el-radio v-model="form.type" label="0">单选</el-radio>
            <el-radio v-model="form.type" label="1">多选</el-radio>
          </el-form-item>
          <el-form-item label="说明" prop="info">
            <el-input type="textarea" :rows="3" style="width: 500px" v-model="form.info" placeholder="请输入说明"/>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="问题及答案" name="2">
          <div style="width: 810px;">
            <div style="width: 276px;float: left">
              <el-form-item label="问题" prop="content">
                <el-input type="textarea" :rows="10" v-model="form.content" placeholder="请输入"/>
              </el-form-item>
            </div>
            <div style="width: 500px;margin-left:10px;float: left">
              <el-form-item label="答案选项(勾选项为答案)" prop="optionList">
                <el-table :data="form.optionList" style="width: 100%" size="mini" :show-header="false" empty-text="请在下方输入选项添加">
                  <el-table-column width="35">
                    <template slot-scope="scope"><el-checkbox v-model="scope.row.r" label=""/></template>
                  </el-table-column>
                  <el-table-column prop="k" width="30"/>
                  <el-table-column width="300">
                    <div slot-scope="scope">
                      <el-input type="textarea" :rows="2" v-if="scope.row.e" v-model="scope.row.v" style="width: 100%"/>
                      <span v-else>{{scope.row.v}}</span>
                    </div>
                  </el-table-column>
                  <el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                      <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="删除" placement="top-end">
                          <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteOptions(scope.$index)"></el-button>
                        </el-tooltip>
                        <el-tooltip v-if="scope.row.e" class="item" effect="dark" content="完成" placement="top-start">
                          <el-button size="mini" type="text" icon="el-icon-circle-check" @click="scope.row.e = false"></el-button>
                        </el-tooltip>
                        <el-tooltip v-else class="item" effect="dark" content="修改" placement="top-start">
                          <el-button size="mini" type="text" icon="el-icon-edit" @click="scope.row.e = true"></el-button>
                        </el-tooltip>
                      </template>
                    </el-table-column>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-input placeholder="请输入添加的选项" v-model="form.optionFlag" size="small">
                <template slot="append">
                  <el-button slot="append" icon="el-icon-plus" @click="addOption">添加</el-button>
                </template>
              </el-input>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="题目解析" name="3">
          <el-form-item label="分析" prop="analyse">
            <el-input type="textarea" :rows="15" style="width: 600px" v-model="form.analyse" placeholder="请输入分析"/>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog title="导入" :visible.sync="importQuestion.open" width="700px" height="1000px" append-to-body>
      <el-form ref="questionForm" :model="importQuestion.form" :rules="rules" label-width="80px">
        <el-form-item label="所属题库" prop="bankId">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-radio-group v-model="form.bankFlag">
                <el-radio label="0" border style="margin: 0">基础题库</el-radio>
                <el-radio label="1" border style="margin: 0">考试题库</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="1.5">
              <el-select v-model="importQuestion.form.bankId" placeholder="请选择所属题库">
                <el-option v-for="item in questionBank.list" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-col>
          </el-row>
<!--          <el-select v-model="importQuestion.form.bankId" placeholder="请选择所属题库">-->
<!--            <el-option v-for="item in questionBank.list" :key="item.id" :label="item.name" :value="item.id"></el-option>-->
<!--          </el-select>-->
        </el-form-item>
        <center>
          <el-upload class="upload-demo" drag :on-change="excelChange" action="#" :auto-upload="false"
                     multiple style="margin-top: 30px" accept=".xls,.xlsx">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              <el-link type="danger" :underline="false" href="javascript:void(0);">只能上传xlsx/xls文件</el-link>
              <el-button type="text" @click="importModel" size="mini" plain>下载模板</el-button>
            </div>
          </el-upload>
        </center>

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion,importExcel} from "@/api/ex/question";
import {listQuestion_bank, listQuestion_bank_ex,} from "@/api/ex/question_bank";

export default {
  name: "Question",
  data() {
    return {
      //添加标题栏
      activeName:'1',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bankId: null,
        content: null,
        type: null,
        options: [],
        answers: null,
        info: null,
        analyse: null,
      },
      // 表单参数
      form: {
        optionList: [],
        optionFlag: '',
        bankFlag: '0',
      },
      // 表单校验
      rules: {
        bankId: [
          { required: true, message: "请选择题库", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "选择类型", trigger: "blur" }
        ],
        optionList: [
          { type: 'array', required: true, message: "至少需要两个选项", trigger: "blur" }
        ],
        answers: [
          { required: true, message: "答案不能为空", trigger: "blur" }
        ]
      },
      //题库列表
      questionBank:{
        list:[]
      },
      //导入
      importQuestion: {
        open:false,
        file:undefined,
        form:{
          bankId:'',
        }
      }
    };
  },
  created() {
    this.getList();
    this.getBankList();
  },
  methods: {
    /** 查询题库列表 */
    getBankList() {
      if (this.form.bankFlag=='0'){
        listQuestion_bank({pageNum:1,pageSize:1000,status:0}).then(response => {
          this.questionBank.list = response.rows;
        });
      }else{
        listQuestion_bank_ex({pageNum:1,pageSize:1000,status:0}).then(response => {
          this.questionBank.list = response.rows;
        });
      }
    },
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bankId: null,
        content: null,
        type: null,
        options: null,
        answers: null,
        info: null,
        analyse: null,
        deptId: null,
        reservedOne: null,
        reservedTwo: null,
        createTime: null,
        bankFlag: '0'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      var obj = {...row};
      const id = obj.id || this.ids;
      //为选项数组中加入是否开启修改按钮
      var list = [];
      obj.optionList.map(o=>{
        o.e = false
        list.push({...o});
      })
      obj.optionList = list;
      this.form = obj;
      this.open = true;
      this.title = "修改题目";
      // getQuestion(id).then(response => {
      //   //为选项数组中加入是否开启修改按钮
      //   var list = [];
      //   var eo = {e:false};
      //   response.data.optionList.map(o=>{
      //     list.push(Object.assign(o,{...eo}));
      //   })
      //   response.data.optionList = list;
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改题目";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //校验
          if (this.form.optionList == undefined || this.form.optionList==null){
            return;
          }
          if (this.form.optionList.length<2){
            this.$modal.msgWarning("至少需要两个选项");
            return;
          }
          var flag = 0;
          for (let i = 0; i < this.form.optionList.length; i++) {
            if (this.form.optionList[i].r) flag++;
          }
          if (this.form.type == '0'){//单选
            if (flag!==1){
              this.$modal.msgWarning("单选题，至少或者只需要一个答案");
              return;
            }
          }else{//多选
            if (flag<2){
              this.$modal.msgWarning("多选题，至少需要两个答案");
              return;
            }
          }
          //执行
          if (this.form.id != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          this.form = { optionList: [], optionFlag: ''}
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + ids + '"的数据项？').then(function () {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ex/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    },
    /** 模板导出 */
    importModel() {
      this.download('ex/question/importModel', {}, `题目模板-${new Date().getTime()}.xlsx`)
    },
    //文件改变事件-直接上传
    excelChange(file,fileList){
      this.$refs["questionForm"].validate(valid => {
        if (valid) {
          //获取后缀
          var suffix = file.name.replace(/.+\./, "").toLowerCase()
          if (suffix != "xls" && suffix != "xlsx"){
            this.$modal.msgWarning('文件格式错误：' + suffix);
            fileList.splice(0);//清空
            return false;
          }
          importExcel(file,this.importQuestion.form.bankId).then(response => {
            this.getList();
            this.importQuestion.form.bankId = '';
            fileList.splice(0);//清空
            this.importQuestion.open = false
          });
        }else{
          fileList.splice(0);//清空
        }
      });
    },
    //添加题目进列表
    addOption(){
      if (this.form.optionFlag == null || this.form.optionFlag == undefined || this.form.optionFlag==''){
        this.$modal.msgWarning("内容不可为空");
        return;
      }
      if (this.form.optionList == undefined || this.form.optionList == null){
        this.form.optionList = [];
      }
      var obj = {};
      obj.k = String.fromCharCode(64 + this.form.optionList.length + 1);
      obj.v = this.form.optionFlag;
      obj.r = false;
      obj.e = false;
      this.form.optionList.push(obj);
      this.form.optionFlag = '';
    },
    //删除选项
    deleteOptions(index){
      this.$delete(this.form.optionList,index);
    }
  },
  watch:{
    'open':function (n,o) {
      if (n!=o){
        this.activeName = '1';
      }
    },
    'form.bankFlag':function (n,o) {
      this.getBankList();
    },
    'importQuestion.form.bankId':function (n,o) {
      this.getBankList();
    }
  }
};
</script>
<style>
.el-input-group__append {
  background-color: #409EFF;
  color: white;
}
.left .el-tooltip__popper, .right .el-tooltip__popper {
  padding: 8px 10px;
}
</style>
